package com.qiwx.pigeon.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.LogUtil;
import com.qiwx.pigeon.Utils.ScreenUtils;
import com.qiwx.pigeon.app.AppContext;


/**
 * 自定义带删除功能的EditText <br />
 * 通过自定属性可设置删除按钮的样式 <br />
 * xmlns:cet="http://schemas.android.com/apk/res-auto"
 * cet:clearable_edit_text_right_drawable="@drawable/radio_tradition_pressed"
 * cet:clearable_edit_text_right_drawable_color="@color/title_bg_blue"
 * 例如：<br />
 * <com.jzg.jcpt.view.ClearableEditText
 * android:id="@+id/etSearchInput"
 * android:layout_width="match_parent"
 * android:layout_height="match_parent"
 * android:layout_toRightOf="@+id/ivMagnifier"
 * android:background="@null"
 * android:gravity="center_vertical"
 * android:maxLength="17"
 * android:paddingLeft="8dp"
 * android:singleLine="true"
 * android:textColor="@color/common_4F535C"
 * android:textSize="14sp"
 * <!-- 指定控件有输入数据后右边出现删除功能的按钮的资源ID -->
 * cet:clearable_edit_text_right_drawable="@drawable/radio_tradition_pressed"
 * <!-- 指定控件有输入数据后右边删除按钮的颜色 -->
 * cet:clearable_edit_text_right_drawable_color="@color/title_bg_blue" />
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public class ClearableEditText extends AppCompatEditText implements View.OnTouchListener, View.OnFocusChangeListener, TextWatcher {

    private Drawable mClearTextIcon;
    private OnFocusChangeListener mOnFocusChangeListener;
    private OnTouchListener mOnTouchListener;

    /**
     * 该控件有输入数据后右边出现删除功能的按钮的资源ID
     */
    private int right_drawable = R.drawable.ic_edittext_del;

    /**
     * 右边删除按钮的颜色
     */
    private int right_drawable_color = R.color.standard_hint_text_color;

    public ClearableEditText(final Context context) {
        super(context);
    }

    public ClearableEditText(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public ClearableEditText(final Context context, final AttributeSet attrs, final int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    @Override
    public void setOnFocusChangeListener(final OnFocusChangeListener onFocusChangeListener) {
        mOnFocusChangeListener = onFocusChangeListener;
    }

    @Override
    public void setOnTouchListener(final OnTouchListener onTouchListener) {
        mOnTouchListener = onTouchListener;
    }


    private boolean isVisible = true;

    @SuppressLint("ResourceAsColor")
    private void init(AttributeSet attrs) {
//        isVisible = (getMaxLines() == 1);
        if (!isVisible) return;
        // 获取自定义属性
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.ClearableEditText);
        if (typedArray != null) {
            // 获取自定义属性右边删除按钮的指定资源
//            isVisible = typedArray.getBoolean(R.styleable.ClearableEditText_clearable_edit_text_right_drawable_isVisible, true);
//            if (!isVisible) {
//                typedArray.recycle();
//                return;
//            }
            // 获取自定义属性右边删除按钮的指定资源
            right_drawable = typedArray.getResourceId(R.styleable.ClearableEditText_clearable_edit_text_right_drawable,
                    R.drawable.ic_edittext_del);
            // 获取右边删除按钮的颜色
            right_drawable_color = typedArray.getColor(R.styleable.ClearableEditText_clearable_edit_text_right_drawable_color,
                    getResources().getColor(R.color.standard_hint_text_color));
            typedArray.recycle();
        }
//        final Drawable drawable = ContextCompat.getDrawable(getContext(), right_drawable);
//        final Drawable wrappedDrawable = DrawableCompat.wrap(drawable); //Wrap the drawable so that it can be tinted pre Lollipop
//        DrawableCompat.setTint(wrappedDrawable, getCurrentHintTextColor());
        Drawable drawable = ContextCompat.getDrawable(getContext(), right_drawable);
        if (drawable != null) {
            mClearTextIcon = DrawableCompat.wrap(drawable);
        }
        if (right_drawable_color != -1)
            DrawableCompat.setTint(mClearTextIcon, right_drawable_color);
        mClearTextIcon.setBounds(0, 0, mClearTextIcon.getIntrinsicHeight(), mClearTextIcon.getIntrinsicHeight());
        setClearIconVisible(false);
        super.setOnTouchListener(this);
        super.setOnFocusChangeListener(this);
        //addTextChangedListener(this);
    }


    @Override
    public void onFocusChange(final View view, final boolean hasFocus) {
        if (!isVisible)
            return;
        if (hasFocus) {
            setClearIconVisible(getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
        if (mOnFocusChangeListener != null) {
            mOnFocusChangeListener.onFocusChange(view, hasFocus);
        }
    }

    @Override
    public boolean onTouch(final View view, final MotionEvent motionEvent) {
        final int x = (int) motionEvent.getX();
        if (mClearTextIcon.isVisible() && x > getWidth() - getPaddingRight() - mClearTextIcon.getIntrinsicWidth()) {
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                setError(null);
                setText("");
            }
            return true;
        }
        return mOnTouchListener != null && mOnTouchListener.onTouch(view, motionEvent);
    }



    @Override
    public final void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
        if (!isVisible)
            return;
        if (isFocused()) {
            setClearIconVisible(s.length() > 0);
        }
        //setEtAddressPadding(this);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    private void setEtAddressPadding(TextView tv) {
        int lineNumber = tv.getLineCount();

        if (lineNumber > 1) {
            LogUtil.e("calculateLines", "超过一行了设置底部paddingbottom");

            int paddingbottom = ScreenUtils.dip2px(AppContext.getContext(), 16);
            tv.setPadding(0, 0, 0, paddingbottom);
        } else {
            LogUtil.e("calculateLines", "没超过一行恢复padding值");
            tv.setPadding(0, 0, 0, 0);
        }
    }

    private void setClearIconVisible(final boolean visible) {
        if (!isVisible)
            return;
        mClearTextIcon.setVisible(visible, false);
        final Drawable[] compoundDrawables = getCompoundDrawables();
        setCompoundDrawables(
                compoundDrawables[0],
                compoundDrawables[1],
                visible ? mClearTextIcon : null,
                compoundDrawables[3]);
    }



}
